<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { scenceFloorFormSchema } from './scence.data'
import { addScence, updateScence } from '@/api/collection/scence';

defineOptions({ name: 'ScenceFloorModal' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const nodeRef = ref()

const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: scenceFloorFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  nodeRef.value = data.node
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.node,
    })
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增楼层' : '编辑楼层'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    let params: any = { ...values, name: values.nameCopy, }
    if (unref(isUpdate)) {
      params = { ...params, type: 2, id: nodeRef.value.id, fileId: values.file?.data?.id }
      await updateScence(params)
    }
    else {
      params = { ...params, type: 2, parentId: nodeRef.value.id, fileId: values.file?.data?.id }
      await addScence(params)
    }
    closeModal()
    emit('success', params)
  } finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>
